package com.kinon.ogt.view.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.EditText;

import com.kinon.ogt.R;
import com.kinon.ogt.api.OgtApi;
import com.kinon.ogt.api.exception.ApiException;
import com.kinon.ogt.api.service.ServiceFactory;
import com.kinon.ogt.utils.RegExUtils;
import com.kinon.ogt.utils.RxUtils;
import com.kinon.ogt.utils.SPrefsUtils;
import com.kinon.ogt.utils.ToastUtils;
import com.kinon.ogt.view.widget.FxToolbar;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;

/**
 * 佛祖保佑 永无BUG
 *
 * @author 339
 * @date 2018/5/17
 */
public class SignUpActivity extends AppCompatActivity {

    private static final long COUNT_DOWN_TIME = 60L;

    @BindView(R.id.toolbar)
    FxToolbar mToolbar;
    @BindView(R.id.et_sign_up_phone_number)
    EditText mEtPhoneNumber;
    @BindView(R.id.btn_sign_up_verify_code)
    Button mBtnVerifyCode;
    @BindView(R.id.et_sign_up_verify_code)
    EditText mEtVerifyCode;
    @BindView(R.id.et_sign_up_password)
    EditText mEtPassword;
    @BindView(R.id.et_sign_up_invite_code)
    EditText mEtInviteCode;
    @BindView(R.id.btn_sign_up)
    Button mBtnSignUp;

    private Disposable mDisposable;
    private OgtApi mOgtApi;

    private String mVerifyCode = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);
        ButterKnife.bind(this);

        initData();
        initView();
    }

    private void initData() {
        mOgtApi = ServiceFactory.getOgtApi();
    }

    private void initView() {
        mToolbar.setTitle("注册");
        mToolbar.setOnBackClickListener(v -> onBackPressed());
        setSupportActionBar(mToolbar);
    }

    @OnClick(R.id.btn_sign_up_verify_code)
    public void onVerifyCodeClicked() {
        String phoneNumber = mEtPhoneNumber.getText().toString();
        if (RegExUtils.isPhoneNumValid(phoneNumber)) {
            getVerifyCode(phoneNumber);
            mDisposable = Flowable.interval(0L, 1L, TimeUnit.SECONDS)
                    .compose(RxUtils.rxSchedulerHelper())
                    .subscribe(aLong -> {
                        if (COUNT_DOWN_TIME - aLong <= 0) {
                            mBtnVerifyCode.setEnabled(true);
                            mBtnVerifyCode.setText("领取验证码");
                            return;
                        }

                        mBtnVerifyCode.setEnabled(false);
                        mBtnVerifyCode.setText(String.format("%s秒后重发", COUNT_DOWN_TIME - aLong));
                    });
            return;
        }

        ToastUtils.showShort(this, "请输入正确的手机号码！");
    }

    private void getVerifyCode(String phoneNumber) {
        mDisposable = mOgtApi.getVerifyCode(phoneNumber)
                .compose(RxUtils.rxSchedulerHelper())
                .compose(RxUtils.handleResult())
                .subscribe(verifyCode -> {
                    if (verifyCode.getPhone().equals(phoneNumber)) {
                        mVerifyCode = verifyCode.getCode();
                    }
                }, throwable -> ToastUtils.showShort(SignUpActivity.this,
                        ((ApiException) throwable).getMsg()));
    }

    @OnClick(R.id.btn_sign_up)
    public void onSignUpClicked() {
        mBtnSignUp.setEnabled(false);
        String phoneNumber = mEtPhoneNumber.getText().toString();
        String verifyCode = mEtVerifyCode.getText().toString();
        String password = mEtPassword.getText().toString();
        String inviteCode = mEtInviteCode.getText().toString();

        if (RegExUtils.isPhoneNumValid(phoneNumber) && RegExUtils.isPasswordValid(password)
                && verifyCode.equals(mVerifyCode)) {
            mDisposable = mOgtApi.attemptSignUp(phoneNumber, password, inviteCode)
                    .compose(RxUtils.rxSchedulerHelper())
                    .compose(RxUtils.handleResult())
                    .subscribe(result -> saveUserInfo(phoneNumber, password, result),
                            throwable -> {
                                mBtnSignUp.setEnabled(true);
                                ToastUtils.showShort(SignUpActivity.this,
                                        ((ApiException) throwable).getMsg());
                            });
            return;
        }

        ToastUtils.showShort(SignUpActivity.this, "验证码或密码错误！");
    }

    private void saveUserInfo(String phoneNum, String password, String result) {
        SPrefsUtils.writeUsername(phoneNum);
        SPrefsUtils.writePassword(password);
        SPrefsUtils.writeToken(result);
        startActivity(new Intent(SignUpActivity.this, MainActivity.class));
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mDisposable) {
            mDisposable.dispose();
            mDisposable = null;
        }
    }
}
